var queues = require('mysql-queues');
const DEBUG = true;
var select = function(connection, callback) {
	var sql = 'select * from role';
	connection.query(sql, function(err, rows) {
		if (err) {
			console.log(err);
			console.log(err.stack);
		}
		callback(rows);
		connection.release();
	});
},
	add = function(connection, data, callback) {
		queues(connection, DEBUG);
		var sql = 'insert into role(roleName) values(?)';
		var trans = connection.startTransaction(); 
		trans.query(sql, [data.roleName], function(err, rows) {
			if (err) {
				console.log(err);
				console.log(err.stack);
				trans.rollback();
			} else {
				trans.commit(function(err, info) {
					console.log(info);
				});
			}
			callback(rows);
		});
		trans.execute();
		console.log('execute addUserRole');
		connection.release();
	},
	delet = function(connection, id, callback) {
		queues(connection, DEBUG);
		var sql = 'delete from role where id=?';
		var trans = connection.startTransaction();
		trans.query(sql, id, function(err, rows) {
			if (err) {
				console.log(err);
				console.log(err.stack);
				trans.rollback();
			} else {
				trans.commit(function(err, info) {
					console.log(info);
				});
			}
			console.log('rows', rows);
			callback(rows);
		});
		trans.execute();
		console.log('execute');
		connection.release();
	},
	update = function(connection, data, callback) {
		queues(connection, DEBUG);
		var sql = 'update role set roleName=? where id=?';
		var trans = connection.startTransaction();
		trans.query(sql, [data.roleName, data.id], function(err, rows) {
			if (err) {
				console.log(err);
				console.log(err.stack);
				trans.rollback();
			} else {
				trans.commit(function(err, info) {
					console.log('info:', info);
				});
			}
			console.log('rows', rows);
			callback(rows);
		});
		trans.execute();
		console.log('execute update');
		connection.release();
	},
	findById = function(connection, id, callback) {
		var sql = 'select * from role where id=?';
		connection.query(sql, id, function(err, rows) {
			callback(rows);
			connection.release();
		});
	},
	checkExist = function(connection, id, callback){
		var sql = 'select * from user_role where roleId=?';
		connection.query(sql, id, function(err,rows){
			callback(rows);
			connection.release();
		});
	},
	checkAllRole = function(connection, id, callback){
		var sql = 'select r.roleName from user u,user_role ur,role r where u.id=ur.userId and ur.roleId=r.id and u.id=?';
		connection.query(sql, id, function(err,rows){
			if(err){
				console.log(err);
				console.log(err.stack);
			}
			callback(rows);
			connection.release();
		});
	};

module.exports = {
	selectRole: select,
	addRole: add,
	deleteRole: delet,
	updateRole: update,
	findById: findById,
	checkExist: checkExist,
	checkAllRole: checkAllRole
};